// 封装 原生的Ajax
(function(global){
    // 以兼容的方式构建 异步请求对象 xhr
    function createXHR() {
        // 现在基本不需要做兼容的处理
        var xhr;
        if(window.XMLHttpRequest){
            // Mozilla, Safari, Chrome, IE7+, ...
            xhr = new XMLHttpRequest();
        } else if(window.ActiveXObject) {
            // IE6 or older
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            alert("您的浏览器不支持Ajax请求");
        }
        return xhr;
    }

    /*
    options = {
        url,
        method,
        async,
        data,
        success: function
    }
     */
    function ajax(options) {
        var async = false;
        if(options.async == undefined || options.async == true){
            // 未设置 或 设置为 true, 则 为 true
            async = true;
        }
        var xhr = createXHR();
        var method = "get";
        if(options.method == "post"){
            method = "post";
        }
        xhr.onload = function(){
            if(xhr.status == 200) {
                options.success(xhr.responseText);
            } else {
                options.success(xhr);
            }
        }
        xhr.open( method, options.url, async);

        if(method == "post"){
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(options.data);
        } else {
            xhr.send();
        }
    }
    global.ajax = ajax;
})(window);